package com.farsunset.cim.client.android;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;

public class Heartbeat extends IdleStateAwareChannelHandler {

	int i = 0;
	//心跳线程
	ThreadPoolExecutor HBExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
	@Override
	public void channelIdle(final ChannelHandlerContext ctx, IdleStateEvent e)
			throws Exception {
		// TODO Auto-generated method stub
		if (e.getState() == IdleState.WRITER_IDLE)
			i++;

		if (i == 3) {
			e.getChannel().close();

			System.out.println("掉了。");
		}
		
		
		
		ChannelBuffer aOut = ChannelBuffers.dynamicBuffer();
		aOut.writeByte(CommandType.PING.id());
    	
        Record rec = Record.forWrite();
        rec.addInt(1000);
        rec.write(aOut);
        
    
           if (e.getState() == IdleState.WRITER_IDLE) {
                System.out.println("WRITER_IDLE");
                //LOGGER.info("WRITER_IDLE");
                
                HBExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                    	// thread-safe. Can be called from any thread.
                        ChannelFuture future = ctx.getChannel().write(new Ping(1000));                         
                        future.addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture aFuture) throws Exception {
                            	System.out.println("cmd sent: ping");
                            }
                        });
                    }
                });    
            }  
		
		
		
		super.channelIdle(ctx, e);
	}
	
	

}